/*
 * pkgmgr.h
 *
 *  Created on: Jan 14, 2009
 *      Author: yospaly
 */

#pragma once

#include <wx/msgdlg.h>
#include <wx/thread.h>

class PkgMaintainThread : public wxThread {
public:
	PkgMaintainThread() : wxThread(wxTHREAD_DETACHED) {}
	virtual ExitCode Entry();
};

class PkgMgr {
	friend class PkgMaintainThread;
public:
	static PkgMgr& get() {
		return self;
	}
	
	void stop_tasks() {
		_stop_tasks = true;
	}
	
	// we can't create process within worker thread,
	// so, we must let GUI thread to handle scripts.
	void end_run_script() {
		_script_running = false;
	}
	
	void run_download_task() {
		_task_type = DOWNLOAD;
		_run_task();
	}
	void run_maintain_task() {
		_task_type = MAINTAIN;
		_run_task();
	}
	
	void set_install_pkgs(const wxArrayString& pkgs) {
		_install_pkgs = pkgs;
	}
	void set_remove_pkgs(const wxArrayString& pkgs) {
		_remove_pkgs = pkgs;
	}
	void set_upgrade_pkgs(const wxArrayString& pkgs) {
		_upgrade_pkgs = pkgs;
	}
	void set_reinstall_pkgs(const wxArrayString& pkgs) {
		_reinstall_pkgs = pkgs;
	}
	
	const wxString& get_download_cache_dir() {
		return _download_dir;
	}
	
	virtual ~PkgMgr();
	
protected:
	void _gen_download_list();
	
	bool _extract_files(const wxString& pkg);
	
	void _begin_run_script() {
		_script_running = true;
	}
	void _wait_run_script() {
		while ( _script_running ) {
			wxThread::Yield();
		}
	}
	
	virtual wxThread::ExitCode _remove_task();
	virtual wxThread::ExitCode _maintain_task();
	virtual wxThread::ExitCode _download_task();
	virtual wxThread::ExitCode _install_task();
	
	virtual bool _is_cached(const wxString& pkg, const wxString& filepath);
	virtual wxString _get_download_filepath(const wxString& path /* relative path */ );
	virtual wxString _get_download_fileurl(const wxString& path /* relative path */ );
	
	virtual void _run_task() {
		_stop_tasks = false;
		PkgMaintainThread* task = new PkgMaintainThread();
		task->Create();
		task->Run();
	}
	
	wxArrayString _install_pkgs;
	wxArrayString _remove_pkgs;
	wxArrayString _upgrade_pkgs;
	wxArrayString _reinstall_pkgs;
	wxArrayString _download_pkgs;
	
	wxString _download_dir;
	unsigned long _download_size;
	
	bool _stop_tasks;
	
	// wxCondition Wait() func no work within worker thread,
	// So, I use a ugly way
	bool _script_running;
	
	static PkgMgr self;
	
	enum _TASK_TYPE {
		REMOVE = 0,
		DOWNLOAD,
		INSTALL,
		MAINTAIN,
	};
	
	_TASK_TYPE _task_type;
	
	PkgMgr();
};

